/*
The MIT License (MIT)

Copyright (c) 2013 Mike Dapiran, Brian May, Richard Pospesel, and Bert Wierenga

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software 
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
*/
#pragma once



#include "Hogshead.Common.h"
#include "..\Interfaces\IContent.h"

namespace Hogshead
{
	namespace Core
	{
		class Scene;
		

		/**
		* ContentLibrary class; This is a Manager class that has Game scope and is responsible for managing all 
		* instances of classes that extend IContent. It manages the memory as an interface over the Factory and
		* internally talks with the Factory as need be. All content classes need to register with the ContentLibrary.
		* Whenever a class needs a pointer to a content instance it must come from the ContentLibrary via
		* one of the methods in ContentLibrary. Whenever a class is done with a pointer to a content instance
		* it must return it to the ContentLibrary via release. The ContentLibrary also holds the loaded Scenes
		* for the game which must communicate with the ContentLibrary for loading and unloading. 
		*
		* @see IContent
		* @see Scene
		* @see IGame
		*/
		class ContentLibrary
		{
		public:

			/**
			* initialize method; called at the beginning of the Game to setup the ContentLibrary.
			* This will get a prototype instance of each Content type in the a HashTable, create 
			* the list of HashTables that store all the instances of classes that extend IContent,
			* and release the registered 
			*/
			static void initialize();

			/**
			* finalize method; called at the end of the Game to cleanup the Content in the ContentLibrary.
			*/
			static void finalize();

			/**
			* registerContentType method; called at the beginning of a game during registration time. 
			* This method is used to let the ContentLibrary know of a class that extends IContent that 
			* we want it to manage.
			*
			* @param T A class that extends IContent.
			*/
			template<class T> static void registerContentType()
			{
				T* t = Factory::acquire<T>();
				if(_prototype_library == NULL)
					_prototype_library = new HashTable<String, IContent*>();

				_prototype_library->add( t->contentName(), t );
			}

			/**
			* getContent method; this method is to be called by any class that wants to get a reference
			* to an specific instance of a class that extends IContent, that is, a piece of content.
			* NOTE: calling this method will increase the reference count of that piece of content.
			*
			* @param T A class that Extends IContent, a content class.
			* @param key The string name for that instance of content. This is a unique identifier.
			*
			* @return Returns a pointer to the requested piece of content.
			*/
			template<class T> static T* getContent(const String& key)
			{
				IContent* result = NULL;
				_content_table[T::contentID()].tryGetValue(key, result);

				if(result)
					result->_ref_count++;

				return (T*)result;
			}
			
			/**
			* explicitLoad method; This is one of two options for loading a piece of content. This method
			* will check to see if the content piece you requested is already loaded. If it is it will return
			* a pointer and increment its reference count. Otherwise, it will load the piece of content
			* set its ref count to 1 and return a pointer to it. This method will call explictLoad on the piece
			* of content before returning.
			* 
			* @param T The type of class, that extends IContent, you are attempting to load.
			* @param in_key The string that uniquely identifies this instance for the class T.
			* @param in_path The path to whatever file actually stores the data for this content instance.
			*
			* @return Returns a pointer to the instance requested.
			*/
			template<class T> static T* explicitLoad(const String& in_key, const String& in_path)
			{
				IContent* potentially_stored;
				IContent* prototype;
				_prototype_library->tryGetValue( T::getContentName(), prototype );

				String key(in_key);

				if(_content_table[prototype->getContentID()].tryGetValue(key, potentially_stored))
				{
					if(potentially_stored->_path.equals( in_path ))
					{
						//already loaded, we're done
						potentially_stored->_ref_count++;
						return (T*)potentially_stored;
					}
					else
					{
						error("You are attempting to use the same key twice");
					}
				}
				//new piece of content, needs to be loaded
				
				IContent* new_content = (IContent*) prototype->instance();
				new_content->_key = in_key;
				new_content->_path = in_path;
				new_content->_ref_count = 1;

				new_content->explicitLoad();

				String hand_off_key = key;
				int id = new_content->getContentID();
				_content_table[id].add(hand_off_key, new_content);
				return (T*)new_content;
			}

			/**
			* loadEmpty will give an empty piece of content or an instance of the content with the key
			*
			* @param in_key The key to assign to the new piece of content
			**/
			template<class T> static T* loadEmpty(const String& in_key, const String& in_path)
			{
				IContent* potentially_stored;
				IContent* prototype;
				_prototype_library->tryGetValue( T::getContentName(), prototype );

				String key(in_key);

				if(_content_table[prototype->getContentID()].tryGetValue(key, potentially_stored))
				{
					if(potentially_stored->_path.equals( in_path ))
					{
						//already loaded, we're done
						potentially_stored->_ref_count++;
						return (T*)potentially_stored;
					}
					else
					{
						error("You are attempting to use the same key twice");
					}
				}
				//new piece of content, needs to be loaded
				
				IContent* new_content = (IContent*) prototype->instance();
				new_content->_key = in_key;
				new_content->_path = in_path;
				new_content->_ref_count = 1;

				//new_content->explicitLoad();

				String hand_off_key = key;
				int id = new_content->getContentID();
				_content_table[id].add(hand_off_key, new_content);

				//handle messages
				MSG msg = {0};
				if(PeekMessage( &msg, 0, 0, 0, PM_REMOVE ))
				{
					TranslateMessage( &msg );
					DispatchMessage( &msg );
				}

				return (T*)new_content;
			}

			template<class T> static T* explicitLoadFromData(const String& in_key, const String& in_path, void* in_data)
			{
				IContent* potentially_stored;
				IContent* prototype;
				_prototype_library->tryGetValue( T::getContentName(), prototype );

				String key(in_key);

				if(_content_table[prototype->getContentID()].tryGetValue(key, potentially_stored))
				{
					if(potentially_stored->_path.equals( in_path ))
					{
						//already loaded, we're done
						potentially_stored->_ref_count++;
						return (T*)potentially_stored;
					}
					else
					{
						error("You are attempting to use the same key twice");
					}
				}
				//new piece of content, needs to be loaded
				
				IContent* new_content = (IContent*) prototype->instance();
				new_content->_key = in_key;
				new_content->_path = in_path;
				new_content->_ref_count = 1;

				new_content->explicitLoadFromData(in_data);

				String hand_off_key = key;
				int id = new_content->getContentID();
				_content_table[id].add(hand_off_key, new_content);

				//handle messages
				MSG msg = {0};
				if(PeekMessage( &msg, 0, 0, 0, PM_REMOVE ))
				{
					TranslateMessage( &msg );
					DispatchMessage( &msg );
				}

				return (T*)new_content;
			}

			/**
			* loadAndParseAssetList method; Used to load a List of Content instances. An AssetList can contain 
			* tags for both ContentXML and AssetList.
			*
			* @param in_path The path to the AssetList xml file.
			*/
			static void loadAndParseAssetList(const String& in_path);

			/**
			* loadAndParseContentXML method; This is one of two options for loading a piece of content. This method
			* will check to see if the content piece you requested is already loaded. If it is it will return
			* a pointer and increment its reference count. Otherwise, it will load the piece of content
			* set its ref count to 1 and return a pointer to it. This method will call readXML on the piece
			* of content before returning.
			*
			* @param in_path The path to the ContentXML to load for this content instance.
			*
			* @return Returns a pointer to the instance requested.
			*/
			static IContent* loadAndParseContentXML(const String& in_path, bool use_environment_variable = true);

			static void write(const char* in_message);

			/**
			* release method; Whenever a class that has aquired a content instance is done with it, it needs to be
			* released to the ContentLibrary for cleanup. Classes that extend IContent must be released to the 
			* ContentLibrary and NEVER to the Factory.
			*
			* @param in_content The content instance to release a pointer from.
			*/
			static void release(IContent* in_content);

			/**
			* purge method; this method is to be called whenever we want the Game to release any unused Content
			* objects to free up memory.
			*/
			static void purge();
			
			/**
			* printOut method; this method is for debugging. It will print out to the console information about
			* each Content object that is in the ContentLibrary.
			*/
			static void printOut();

			/**
			* Sets the content path value to a string constant.
			*/
			static void setContentPath(const String& in_path);

			/**
			* Called early in initialization to set the Windows Environment Variable name
			* that defines where the root directory of content for our game.
			*/
			static void setContentEnvironmentVariable(const String& in_variable_name);

			/**
			* Called to get the complete string to that holds the absolute path to a 
			* content file.
			*
			* @param in_local_path The relative path of the Content we want to load.
			*
			* @return Returns the absolute path to the piece of Content.
			*/
			static String getCompleteContentString(const String& in_local_path);
			static String getRelativePath(const String& in_abso_path);

			/**
			* Used to check to see if a Prefab is loaded by key
			*
			* @param in_key the key the Prefab is refeenced by.
			*
			* @return Returns true if the Prefab is already stored.
			*/
			static bool prefabIsLoaded(const String& in_key);

			static const String& getContentPath()
			{
				return _content_path;
			}

		private:
			/* The Environment Variable that tells us where the game's content is */
			static String _content_path;

			/* a safety check for whether we've setup our content environment variable or not. */
			static bool _given_env_var;

			friend class IGame;
			friend class IContent;

			/**
			* getScene method; to be used exclusively by classes that extend IGame. This returns pointers
			* to Scene instances by request without increasing ref count. Saves having to manage Scenes
			* in two places.
			*
			* @param in_key The name of the Scene.
			*
			* @return Returns the requested Scene.
			*/
			static Scene* getScene(const String& in_key);

			
			//  prototype dictionary
			static HashTable<String, IContent*>* _prototype_library;
			
			// used to map const char* to individual Resources
			static HashTable<String,IContent*>* _content_table;

			static Logger* _logger;

			//the number of classes that registered as Content types.
			static int _num_types;			
		};
	}
}